using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Devices.Sensors;
using Microsoft.Xna.Framework;
using WPCoco;
using Microsoft.Xna.Framework.Input.Touch;
using WPCoco.Controllers;
using FluidDemo.Model;
using Microsoft.Xna.Framework.Graphics;
using WPCoco.Graphics;

namespace FluidDemo.Scenes
{
    public class SimulationLayer : AffineNode
    {
        public SimulationLayer()
        {
            Width = Screen.Width; Height = Screen.Height;
            Anchor = new Vector2(0, 0);

            NeedUpdate = true;

            IsRunningChange += new EventHandler(MainScene_IsRunningChange);

            env.Bounds = new RectangleF(0, 0, Screen.Width, Screen.Height);

            env.AddEntity(new Atractor() { Center = Screen.Center, Radius = 80, ForceAmount = 9.8f * 20 });

            for (int i = -2; i <= 2; i++)
            {
                for (int j = -1; j <= 1; j++)
                {
                    env.AddEntity(new Circle() { Center = Screen.Center + new Vector2(i * 120, j * 120), Radius = 30 });
                }
            }

            //env.AddCollitionable(new Circle() { Center = Screen.Center + new Vector2(200, 0), Radius = 150 });
            //env.AddCollitionable(new Circle() { Center = Screen.Center - new Vector2(100, 0), Radius = 150 });

            acc.CurrentValueChanged += (o, e) =>
            {
                /*
                float angle = (float)Math.Atan2(e.SensorReading.Acceleration.X, e.SensorReading.Acceleration.Y);
                angle = MathHelper.ToDegrees(angle);
                p.ParticleAngle = angle;
                */
                Vector2 g = new Vector2(e.SensorReading.Acceleration.Y, e.SensorReading.Acceleration.X);
                g.Normalize();
                g *= -9.8f * 5;
                env.Gravity = g;
            };
        }

        Accelerometer acc = new Accelerometer();

        void MainScene_IsRunningChange(object sender, EventArgs e)
        {
            if (IsRunning)
            {
                acc.Start();
                ControllerManager.Shared.TouchScreen.Dragging += new EventHandler<CustomEventArgs<GestureSample>>(TouchScreen_Dragging);
            }
            else 
            {
                acc.Stop();
                ControllerManager.Shared.TouchScreen.Dragging -= new EventHandler<CustomEventArgs<GestureSample>>(TouchScreen_Dragging);
            }
        }

        void TouchScreen_Dragging(object sender, CustomEventArgs<GestureSample> e)
        {
            if (env.Particles.Count >= (DemoSettings.IsDevice ? 400 : 1000))
            {
                ((Atractor)env.Entities[0]).Center = e.Value.Position;
                return;
            }
            Particle p = new Particle(e.Value.Position, 0.3f);
            p.Radius = 5;
            p.Update();
            env.AddParticle(p);
        }

        PhisicalEnvironment env = new PhisicalEnvironment();

        public PhisicalEnvironment Environment
        {
            get { return env; }
            set { env = value; }
        }

        protected override void SelfUpdate(GameTime gameTime)
        {
            env.Update((float)gameTime.ElapsedGameTime.TotalSeconds);
        }

        Texture2D texture = Coco.Load<Texture2D>("fire");

        public override void SelfDraw(GameTime gameTime)
        {
            if (env.Particles.Count > 0)
            {
                CachedSpriteBatch batch = SpriteBatchCache.GetVolatile();
                batch.Begin(SpriteSortMode.Deferred, BlendState.Additive, null, null, null, null, WorldMatrix.Shared.CurrentMatrix);
                Vector2 origin = new Vector2(texture.Width / 2, texture.Height / 2);
                Color color = Color.White;
                float scale = (2 * env.Particles[0].Radius) / texture.Width;
                if (DemoSettings.IsDevice)
                    scale *= 4.5f;
                else
                    scale *= 4;

                color = Color.Cyan;

                for (int i = 0; i < env.Particles.Count; i++)
                {
                    Particle p = env.Particles[i];
                    
                    //Vector2 v = p.Velocity / 5;
                    //v.Normalize();

                    //
                    //color = Color.Lerp(Color.Cyan, Color.Cyan, p.Velocity.Length());

                    //
                    //color = new Color(1,
                    //                  (float)Math.Min(1, p.Velocity.X / 5.0f),
                    //                  (float)Math.Min(1, p.Velocity.Y / 5.0f),
                    //                  1);

                    batch.Draw(texture, p.Position, null, color, 0, origin, scale, SpriteEffects.None, 0);
                }
                batch.End();
            }


            
            


        }


    }
}
